//
//  AppDelegate.m
//  ENTBoostChat
//
//  Created by zhong zf on 14-8-2.
//  Copyright (c) 2014年 EB. All rights reserved.
//

#import "AppDelegate.h"
#import "BlockUtility.h"
#import <CoreData/CoreData.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //设置服务地址(必须要在获取实例前调用才有效)
    [ENTBoostKit setServerAddress:@"test-lc.entboost.com:18012"];
    
    //生成登录界面控制器
    UIStoryboard* logonStoryboard = [UIStoryboard storyboardWithName:@"Logon" bundle:nil];
    self.logonViewController = [logonStoryboard instantiateViewControllerWithIdentifier:@"logonController_ID"];
    self.splashScreenController = [logonStoryboard instantiateViewControllerWithIdentifier:@"splashScreenController_ID"];

    //生成TabBarController实例
    self.tabBarController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"tabBarController_ID"];
    
    self.window.rootViewController = self.splashScreenController;
    [self.window makeKeyAndVisible];
    
    //执行初始化恩布SDK环境
    [self initENTBoostKit];
    
    return YES;
}

//初始化恩布SDK环境
- (void)initENTBoostKit
{
    //测试应用ID可到恩布官网申请获取 www.entboost.com
    NSString* appId =@"278573612908";
    NSString* appKey =@"ec1b9c69094db40d9ada80d657e08cc6";
    
    __block dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    __weak typeof(self)safeSelf = self; //安全引用self对象,防止Block循环引用
    [BlockUtility performBlockInGlobalQueue:^{
        //获取SDK接口全局单实例
        ENTBoostKit* ebKit = [ENTBoostKit sharedToolKit];
        
        //设置尝试自动登录
        ebKit.wantAutoLogon = NO;
        
        [ebKit registerWithAppId:appId appKey:appKey andDelegate:self.tabBarController onCompletion:^{
            NSLog(@"恩布SDK初始化成功");
            dispatch_semaphore_signal(sem);
            [BlockUtility performBlockInMainQueue:^{ //主线程中执行
                if (!ebKit.wantAutoLogon) {//非自动登录
                    self.window.rootViewController = self.logonViewController; //显示登录界面
                    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide]; //显示状态栏
                }
                
                safeSelf.logonViewController.loginButton.enabled = YES; //启用登录按钮
            }];
        } onFailure:^(NSError *error) {
            NSLog(@"恩布SDK初始化失败, code = %i, msg = %@", error.code, error.localizedDescription);
            dispatch_semaphore_signal(sem);
            [BlockUtility performBlockInMainQueue:^{ //主线程中执行
                //提示重新初始化
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:@"应用初始化失败, 请重试" delegate:safeSelf cancelButtonTitle:@"重试" otherButtonTitles:nil, nil];
                [alertView show];
            }];
            
        }];
    }];
    dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 3.0f * NSEC_PER_SEC)); //最长等待3秒
}

//定义的委托, 提示初始化失败后再次执行初始化
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self initENTBoostKit];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    //更新应用图标上数字
    application.applicationIconBadgeNumber = 0;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
